package com.springboot.demo.io;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

import com.springboot.demo.constant.CommonConstant;

/**
 * NIO服务端
 *
 * @author supu
 * @since 2020-11-25 13:44
 **/
public class ServerSocketChannelServer {
    private Selector selector;

    public static void main(String[] args) {
        ServerSocketChannelServer newIoServer = new ServerSocketChannelServer();
        newIoServer.startServer();
    }

    private void startServer() {
        // 1、初始化服务
        initServer();
        // 2、接收事件处理
        acceptEvent();
    }

    private void acceptEvent() {
        while (true) {
            try {
                int fds = selector.select();
                if (fds > 0) {
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if (key.isAcceptable()) {
                            acceptHandler(key);
                        } else if (key.isReadable()) {
                            readHandler(key);
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private void initServer() {
        try {
            selector = Selector.open();

            ServerSocketChannel socketChannel = ServerSocketChannel.open();
            socketChannel.configureBlocking(false);
            socketChannel.bind(new InetSocketAddress(CommonConstant.LOCAL_PORT));

            socketChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void acceptHandler(SelectionKey key) {
        try {
            ServerSocketChannel socketChannel = (ServerSocketChannel) key.channel();
            SocketChannel client = socketChannel.accept();
            client.configureBlocking(false);

            ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4096);
            client.register(selector, SelectionKey.OP_READ, byteBuffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void readHandler(SelectionKey key) {
        try {
            ByteBuffer byteBuffer = (ByteBuffer) key.attachment();
            SocketChannel client = (SocketChannel) key.channel();
            byteBuffer.clear();

            while (true) {
                int read = client.read(byteBuffer);
                if (read > 0) {
                    // 准备读取，重置状态位
                    byteBuffer.flip();
                    if (byteBuffer.hasRemaining()) {
                        byte[] bytes = new byte[byteBuffer.limit()];
                        byteBuffer.get(bytes);
                        System.out.println(client.getRemoteAddress() + " send data : " + new String(bytes));

                        // 写回返回内容
                        byteBuffer.compact();
                        byteBuffer.put(CommonConstant.getResponseContent().getBytes());
                        byteBuffer.flip();

                        client.write(byteBuffer);
                    }
                    byteBuffer.clear();
                } else if (read == 0) {
                    System.out.println("read over");
                    break;
                } else {
                    client.close();
                    System.out.println("client closed");
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
